﻿using System;
using System.ComponentModel;
using System.Configuration;
using System.Linq;
using System.Windows;
using TestBat.ISettings;
using TestBat.IViewModels.Dialogs;
using TestBat.IViewModels.Windows;
using TestBat.ServiceLocator;
using TestBat.Views.Windows;

namespace TestBat.Views
{
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            // setup GuyWire
            var guyWireClassKey = ConfigurationManager.AppSettings.Keys.Cast<string>().FirstOrDefault(k => "guywire".Equals(k.ToLowerInvariant()));
            var guyWireClass = ConfigurationManager.AppSettings[guyWireClassKey];
            var type = Type.GetType(guyWireClass);
            guyWire = (IGuyWire.IGuyWire)Activator.CreateInstance(type);
            // start GuyWire
            guyWire.Wire();

            // enable logging
            log4net.Config.XmlConfigurator.Configure();

            // check for first start
            IExeSettings settings = DefaultServiceLocator.Get<IExeSettingsPersister>().Load();
            if (settings.FirstStart)
            {
                StartSetupWizardWindow();
            }
            else
            { // not first start
                StartMainWindow();
            }
        }

        protected override void OnExit(ExitEventArgs e)
        {
            guyWire.Dewire();

            base.OnExit(e);
        }

        private void StartSetupWizardWindow()
        {
            var viewModel = DefaultServiceLocator.Get<ISetupWizardWindowViewModel>();

            // inform the DialogMediator about the DialogViewModelContainer
            DefaultServiceLocator.Get<IDialogMediator>().DialogViewModelContainer = viewModel;

            // create and show the window
            var window = DefaultServiceLocator.Get<SetupWizardWindow>();
            window.DataContext = viewModel;
            MainWindow = window;
            window.Show();

            viewModel.CloseEvent += (object sender, EventArgs e) => window.Close();

            window.Closing += (object sender, CancelEventArgs args) =>
            {
                StartMainWindow();
            };
        }

        private void StartMainWindow()
        {
            // create the view-model
            var viewModel = DefaultServiceLocator.Get<IMainWindowViewModel>();

            // inform the DialogMediator about the DialogViewModelContainer
            DefaultServiceLocator.Get<IDialogMediator>().DialogViewModelContainer = viewModel;

            // create and show the window
            var window = DefaultServiceLocator.Get<MainWindow>();
            window.DataContext = viewModel;
            MainWindow = window;
            window.Show();
        }

        private IGuyWire.IGuyWire guyWire;
    }
}
